Page({
  data: {
    id: null,
    buyNumber: 1,
    productBanners: []
  },
  onLoad(options) {
   // options = { id: '1027887380534054912' }
    if (!options) {
      this.handleError()
      return
    }
    var id = options.id
    if (!id) {
      this.handleError()
      return
    }
    this.setData({
      id: id
    })
    this.initDetails()
  },
  handleError() {
    getApp().util.showToast('缺少参数')
    my.navigateTo({
      url: '/pages/article/index/index',
    })
  },
  onShareAppMessage() {
    return {
      title: this.data.name,
      path: '/pages/product/details/index?id=' + this.data.id,
    };
  },
  initDetails() {
    getApp().network.get(getApp().api.productDetails.replace('$ID', this.data.id)).then(res => {
      my.setNavigationBarTitle({
        title: res.name
      })
      var productBanners = []
      res.largeImage.split(',').forEach(item => {
        productBanners.push(getApp().util.getFileView(item))
      })
      this.setData({
        ...res,
        productBanners
      })
      console.log(this.data)
    })
  },
  handleBuyNumberChange(value) {
    this.setData({
      buyNumber: value
    })
  },
  goShop() {
    my.switchTab({
      url: '/pages/product/index/index',
    })
  },
  onBuyNumberChange(event) {
    this.setData({
      buyNumber: event.detail
    });
  },
  doBuyProduct() {
    getApp().verifyLogin().then(res => {
      getApp().getOpenId().then(openId => {
        this.setData({
          openId: openId
        })
        this.doCreateOrder()
      })
    })
  },
  async doCreateOrder() {
    var orderNo = await getApp().network.post(getApp().api.createProductOrder, {
      productId: this.data.id,
      productNumber: this.data.buyNumber,
      openId: this.data.openId
    })
    getApp().getOpenId().then(openId => {
      this.doPay(orderNo, openId)
    })
  },
  doPay(orderNo, openId) {
    getApp().network.post(getApp().api.doPrepay, {
      openId: openId,
      tradeType: 'MINI_PROGRAM',
      payMethod: 'zfb',
      orderNo: orderNo
    }).then(res => {
      console.log(res)
      var tradeNo = res.trade_no
      my.tradePay({
        tradeNO: tradeNo,
        success: res => {
          var resultCode =res.resultCode
          if(resultCode==='9000'){
            getApp().util.showToast('支付完成')
          }
        },
        fail: error => {
          console.error('调用 my.tradePay 失败: ', JSON.stringify(error));
          getApp().util.showToast('支付失败')
        },
      });
    })
  },
});
